package com.chl.xadmin.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chl.xadmin.common.vo.Result;
import com.chl.xadmin.sys.entity.User;
import com.chl.xadmin.sys.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chl
 * @since 2023-09-29
 */
@Api(tags = "用户管理")
@RestController
@RequestMapping("/sys/user")
//@CrossOrigin // 解决跨域问题
public class UserController {
    @Autowired
    private IUserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @ApiOperation("查询所有用户信息")
    @GetMapping("/all")
    public Result<List<User>> getAllUser() {
        List<User> list = userService.list();
        return Result.success(list, "查询所有用户信息成功");
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody User user) {
        Map<String, Object> data = userService.login(user);
        if(data != null) {
            return Result.success(data);
        }
        return Result.error("用户名或密码错误");
    }

    @ApiOperation("查询用户信息")
    @GetMapping("/info")
    public Result<Map<String, Object>> getUserInfo(@RequestParam("token") String token) {
        // 通过token获取用户信息，从redis中获取。
        Map<String, Object> data = userService.getUserInfo(token);
        if(data != null) {
            return Result.success(data);
        }
        return Result.error("登录过期，请重新登录");
    }

    @ApiOperation("用户退出")
    @PostMapping("/logout")
    public Result<?> logout(@RequestHeader("X-Token") String token) {
        userService.logout(token);
        return Result.success("退出成功");
    }

    @ApiOperation("分页查询用户信息")
    @GetMapping("/list")
    public Result<?> getUserListPage(@RequestParam(value = "username", required = false) String username,
                                     @RequestParam(value = "phone", required = false) String phone,
                                     @RequestParam(value = "pageNumber") Long pageNumber,
                                     @RequestParam(value = "pageSize") Long pageSize) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasLength(username), User::getUsername, username);
        wrapper.eq(StringUtils.hasLength(phone), User::getPhone, phone);
        Page<User> page = new Page<>(pageNumber, pageSize);
        userService.page(page, wrapper);
        Map<String, Object> data = new HashMap<>();
        data.put("total", page.getTotal());
        data.put("rows", page.getRecords());
        return Result.success(data);
    }

    @ApiOperation("添加用户")
    @PostMapping
    public Result<?> addUser(@RequestBody User user) {
        // 密码加密，即使密码一样，加密后的字符串也不一样
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userService.addUser(user);
        return Result.success("添加用户成功");
    }

    @ApiOperation("修改用户信息")
    @PutMapping
    public Result<?> updateUser(@RequestBody User user) {
        // 表示不修改密码
        user.setPassword(null);
        userService.updateUser(user);
        return Result.success("修改用户成功");
    }

    @ApiOperation("根据id查询用户信息")
    @GetMapping("/{id}")
    public Result<User> getUserById(@PathVariable("id") Integer id) {
        User user = userService.getUserById(id);
        return Result.success(user);
    }

    @ApiOperation("删除用户")
    @DeleteMapping("/{id}")
    public Result<User> deleteUserById(@PathVariable("id") Integer id) {
        userService.deleteUserById(id);
        return Result.success("删除用户成功");
    }

    @ApiOperation("上传头像")
    @PostMapping("/upload")
    public Object upload(MultipartFile file, HttpServletRequest request){
        // 获取项目相对路径
        String path = System.getProperty("user.dir");
        // 生成图片存储目录
        File imagePath = new File(path+"/src//main/resources/static/images");
        // 时间格式化
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 时间目录
        String directory = simpleDateFormat.format(new Date());
        File imageResultPath = new File(imagePath + "\\" + directory);
        // 判断目录是否存在，不存在则创建
        if(!imageResultPath.exists()){
            imageResultPath.mkdirs();
        }
        // 后缀
        String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
        // 新文件名
        String newFileName= UUID.randomUUID().toString().replaceAll("-", "")+suffix;
        System.out.println("图片路径：" + imageResultPath);
        System.out.println("图片名：" + newFileName);
        System.out.println("存储路径："+imageResultPath + "\\" + newFileName);
        // 创建新文件
        File newFile = new File(imageResultPath + "\\" + newFileName);


        try {
            file.transferTo(newFile);
            //协议 :// ip地址 ：端口号 / 文件目录(/images/2020/03/15/xxx.jpg)
            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/images/" + directory + "/" + newFileName;
            System.out.println("图片上传，访问URL：" + url);
            Map<String, Object> data = new HashMap<>();
            data.put("avatar", url);
            return Result.success(data);
        } catch (IOException e) {
            return Result.error("用户头像上传失败");
        }
    }
}
